<?php

/**
 * 店铺公共函数
 * @version 1.0
 * @author ezhu <ezhu@jipukeji.com>
 */


/**
 * 数组进行整数映射转换
 * @param array $map  映射关系二维数组  array(
 *                             '字段名1'=>array(映射关系数组),
 *                             '字段名2'=>array(映射关系数组),
 *                             ......
 *                                       )
 *
 */
function int_to_string(&$data, $map = array('status' => array(1 => '<span class="text-success">正常</span>', -1 => '删除', 0 => '<span class="text-cancel">禁用</span>', 2 => '未审核', 3 => '草稿'))){
    if($data === false || $data === null){
        return $data;
    }
    $data = (array) $data;
    foreach($data as $key => $row){
        foreach($map as $col => $pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}


/**
 * 生成商品/优惠券等唯一编号
 * 格式：1404306C49
 * @author Max.Yu <max@jipu.com>
 */
function create_uniqid_sn($len){
    $uniqid = strtoupper(md5(uniqid()));
    $uniqid = substr($uniqid, 0, $len);
    return date('Ymd').$uniqid;
}


/**
 * 店铺后台子菜单
 */
function store_sub_menu($menu=array(),$key=''){
    if(empty($menu) || empty($key)){
        return array();
    }
    if(isset($menu[$key])){
        return $menu[$key];
    }else{
        return array();
    }
}


/**
 * 获取商品分类名称
 * @author Max.Yu <max@jipu.com>
 */

function getCategoryNameById($cid = null){
    if(empty($cid)){
        return false;
    }
    $categoryName = M('ItemCategory')->where('id='.$cid)->getField('name');
    return $categoryName;
}


/**
 * 生成唯一标识码
 * 格式：DD931A971596273B
 * @author Max.Yu <max@jipu.com>
 */
function build_unique_code($len, $i){
    $unique_code = md5(uniqid().$i);
    $unique_code = substr($unique_code, 0, $len);
    return $unique_code;
}


/**
 * 获取商品评价回复
 * @param  integer $id  商品评价id
 * @author Justin <justin@jipu.com>
 */
function get_item_comment_reply($id = null){
    if($id){
        return M('ItemComment')->where('pid='.$id)->find();
    }
}


/**
 * 获取分类下拉列表，如下类型
 * |-
 *   |-
 * @param string $table            表名
 * @param unknown $option          自定义选项，可定义select名称等
 * @param unknown $where           自定义查询条件,第一层的pid=0，在初始化的时候需要给
 * @param string $field            自定义查询字段
 * @param string $order            排序
 * @return multitype:|string
 */

function getSelect($table='',$option=array(),$where=array(),$field='id, pid, name',$order='sort desc'){
    $returnInfo = null;

    if(empty($table) || empty($option)){
        return array();
    }
    $model = M($table);

    $name = $option['name'] ? : 'name';
    $title = $option['title'] ? : 'name';
    $id = $option['id'] ? : 'id';
    $pid = $option['pid'] ? : 'pid';


    //默认查询条件
    if(empty($where)){
        $where['status'] = 1;
        $where[$pid] = 0;
    }

    //获取一级分类列表
    $firstCat = $model->where($where)->order($order)->field($field)->select();
    $returnInfo = $returnInfo.'<select name="'.$name.'">';
    $returnInfo.= '<option value="0">请选择</option>';
    foreach($firstCat as $cat_1){
        $returnInfo = $returnInfo.'<option value="'.$cat_1[$id].'">'.$cat_1[$title].'</option>';

        //获取二级分类列表
        $where[$pid] = $cat_1[$id];
        $secondCat = $model->where($where)->order($order)->field($field)->select();
        if(!empty($secondCat)){
            foreach($secondCat as $cat_2){
                $returnInfo = $returnInfo.'<option value="'.$cat_2[$id].'">&nbsp;&nbsp;&nbsp;&nbsp;|—'.$cat_2[$title].'</option>';

                //获取三级分类列表
                $where[$pid] = $cat_2[$id];
                $thirdCat = $model->where($where)->order($order)->field($field)->select();
                if(!empty($thirdCat)){
                    foreach($thirdCat as $cat_3){
                        $returnInfo = $returnInfo.'<option value="'.$cat_3[$id].'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|—'.$cat_3[$title].'</option>';
                    }
                }
            }
        }
    }
    $returnInfo = $returnInfo.'</select>';

    return $returnInfo;
}



/**
 * 获取订单项目信息
 * @author Max.Yu <max@jipu.com>
 */
function get_order_item($order_id){
    $order_item = array();
    if(empty($order_id) || is_nan($order_id)){
        return false;
    }

    //实例化订单项目模型
    $order_model = M('OrderItem');

    //定义返回或者操作的字段
    $field = '*, (price * quantity) as subtotal';

    //查询条件初始化
    $where['order_id'] = array('in', $order_id);

    //获取订单项目列表
    $order_item = $order_model->where($where)->order('id asc')->field($field)->select();

    foreach($order_item as $key => &$value){
        $value['spec'] = custom_unserialize($value['spec'], 1, '，');
        //规格图片
        $pic = M('PropertyOption')->getFieldByCode($value['item_code'], 'pic');
        //不存在则为封面图片
        $pic && $value['thumb'] = $pic;
    }

    return $order_item;
}

/**
 * 统计订单商品项目总数量（total_quantity）
 * @author Max.Yu <max@jipu.com>
 */
function count_order_item($order_id){
    $result = array(
        'total_quantity' => 0,
    );

    if(empty($order_id) || is_nan($order_id)){
        return $result;
    }

    //实例化订单项目模型
    $order_item_model = M('OrderItem');

    //定义返回或者操作的字段
    $field = 'SUM(quantity) AS total_quantity';

    //查询条件初始化
    $where['order_id'] = array('in', $order_id);;

    //获取订单数量统计信息
    $data = $order_item_model->where($where)->field($field)->select();
    if($data[0]['total_quantity']){
        $result['total_quantity'] = $data[0]['total_quantity'];
    }
    return $result;
}


/**
 * 利用PHPExcel生成excel文件
 * @param string  $fileName 文件名
 * @param array $headArr  表头
 * @param array $data   导出数据
 * @author Max.Yu <max@jipu.com>
 * 备注：导出数据二维数组的元素个数需与表头数组的元素个数一致
 */
function createExcel($fileName, $headArr, $data, $widthArr = null){
    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
    import("Org.PHPExcel.PHPExcel", '', '.php');
    import("Org.PHPExcel.PHPExcel.Writer.Excel5", '', '.php');
    import("Org.PHPExcel.PHPExcel.IOFactory", '', '.php');
    import("Org.PHPExcel.PHPExcel.Style.Alignment", '', '.php');

    //对数据进行检验
    if(empty($data) || !is_array($data)){
        die("data must be a array");
    }

    //检查文件名
    if(empty($fileName)){
        exit;
    }

    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";

    //创建PHPExcel对象，注意不能少了"\"
    $objPHPExcel = new \PHPExcel();

    //$objProps = $objPHPExcel->getProperties();
    //设置表头行高
    $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);

    //设置表头
    $key = ord("A");
    foreach($headArr as $v){
        $column = chr($key);

        //设置字体：加粗
        $objPHPExcel->getActiveSheet()->getStyle($column.'1')->getFont()->setBold(true);

        //设置列宽
        $width = (isset($widthArr) && isset($widthArr[$column])) ? intval($widthArr[$column]) : 20;

        $objPHPExcel->getActiveSheet()->getColumnDimension($column)->setWidth($width);

        //设置水平对齐：居左
        $objPHPExcel->getActiveSheet()->getStyle($column)->getAlignment()->setHorizontal('left');

        //设置垂直对齐：居中
        $objPHPExcel->getActiveSheet()->getStyle($column)->getAlignment()->setVertical('center');
        $objPHPExcel->getActiveSheet()->getStyle($column.'1')->getAlignment()->setVertical('center');

        //设置表头单元格字符
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.'1', $v);

        $key += 1;
    }

    //准备导出写入的数据
    $rownum = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach($data as $key => $rows){ //行写入
        //设置行高
        $objPHPExcel->getActiveSheet()->getRowDimension($rownum)->setRowHeight(28);

        $span = ord("A");
        foreach($rows as $keyName => $value){//列写入
            $j = chr($span);
            $objActSheet->setCellValue($j.$rownum, $value);
            $span++;
        }
        $rownum++;
    }

    //处理文件名中文乱码问题
    //$fileName = iconv("utf-8", "gb2312", $fileName);
    //sheet命名
    $objPHPExcel->getActiveSheet()->setTitle($fileName);

    //设置活动单元表
    $objPHPExcel->setActiveSheetIndex(0);

    //设置HTTP报头
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    //写入导出数据
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

    //生成的excel文件通过浏览器下载
    $objWriter->save('php://output');
    exit;
}


/**
 * 获取店铺ID
 * @author BUDDHA <[email address]>
 * @DateTime 2017-04-16T11:21:32+0800
 * @return   [type]                   [description]
 */
function storeId(){
    $store = A('seller','Event')->getSellerInfo();
    return $store['store_id'];
}

/*
 * 获取 商家 商品分类下拉列表 (获取到第二层)
 * @author wolfHua <max@jipu.com>
 */

function getCategorySelectOne(){
    $returnInfo = null;
    //获取一级分类列表
    $firstCat = getCategoryClass();

    //定义返回或者操作的字段
    $field = 'id, pid, name';

    //定义排序条件
    $order = 'sort asc, id asc';

    $returnInfo = $returnInfo.'<select name="cid">';
    foreach($firstCat as $cat_1){
        $returnInfo = $returnInfo.'<optgroup label="'.$cat_1['name'].'"></optgroup>';
        //获取二级分类列表
        $where['pid'] = $cat_1['id'];
        $where['status'] = 1;
        $secondCat = M('ItemCategory')->where($where)->order($order)->field($field)->select();
        if(!empty($secondCat)){
            foreach($secondCat as $cat_2){
                $returnInfo = $returnInfo.'<option value="'.$cat_2['id'].'">&nbsp;&nbsp;&nbsp;&nbsp;|—'.$cat_2['name'].'</option>';
            }
        }
    }
    $returnInfo = $returnInfo.'</select>';

    return $returnInfo;
}

/*
 * 获取商家的商品分类 [一级分类]
 * @author wolfHua <max@jipu.com>
 */
function getCategoryClass(){
    $orderItemInfo = array();
    $returnInfo = null;

    $store = A('seller','Event')->getSellerInfo();
    $store_id = $store['store_id'];

    $storeClass = M('storeSellCategory')->where(array('store_id'=>$store_id))->select();
    $ids = array();
    foreach ($storeClass as $key=>$val){
        $ids[] = $val['sell_cid_1'];
        $ids[] = $val['sell_cid_2'];
        $ids[] = $val['sell_cid_3'];
    }
    if(!empty($ids)){
        $where['id'] = array('in',$ids);
        $where['pid'] = 0;
        $where['status'] = 1;
    }
    //$list = M('ItemCategory')->where($where)->order('pid asc,sort asc')->select();
    //定义返回或者操作的字段
    $field = 'id, pid, name';

    //定义排序条件
    $order = 'sort asc, id asc';

    //获取一级分类列表
    $firstCat = M('ItemCategory')->where($where)->order($order)->field($field)->select();
    return $firstCat;
}

/*
 * 获取商家的商品分类 [二级分类]
 * @author wolfHua <max@jipu.com>
 */
function getCategoryClassTwo(){
    $returnInfo = null;

    $store = A('seller','Event')->getSellerInfo();
    $store_id = $store['store_id'];

    $storeClass = M('storeSellCategory')->where(array('store_id'=>$store_id))->select();
    $ids = array();
    foreach ($storeClass as $key=>$val){
        $ids[] = $val['sell_cid_1'];
        $ids[] = $val['sell_cid_2'];
        $ids[] = $val['sell_cid_3'];
    }
    if(!empty($ids)){
        $where['id'] = array('in',$ids);
        $where['pid'] = 0;
        $where['status'] = 1;
    }
    //$list = M('ItemCategory')->where($where)->order('pid asc,sort asc')->select();
    //定义返回或者操作的字段
    $field = 'id, pid, name';

    //定义排序条件
    $order = 'sort asc, id asc';

    //获取一级分类列表
    $firstCat = M('ItemCategory')->where($where)->order($order)->field($field)->select();
    $data = array();
    $flag = 0;
    foreach($firstCat as $cat_1){
        //获取二级分类列表
        $map['pid'] = $cat_1['id'];
        $map['status'] = 1;
        $secondCat = M('ItemCategory')->where($map)->order($order)->field($field)->select();
        if(!empty($secondCat)){
            foreach($secondCat as $cat_2){
                $data[$flag] = $cat_2;
                $flag ++;
            }
        }
        //return $secondCat;
    }
    return $data;
}

/**
 * 获取拼团订单人数
 * @author buddha <[email address]>
 * @param  [type] $join_id [description]
 * @return [type]          [description]
 */
function get_join_count( $join_id ){
    return M('Join_order')->where('join_id='.$join_id)->count();
}




